package com.eairlv.route.demo.config.route;

import com.eairlv.route.client.configuration.RouteProperties;
import com.eairlv.route.client.entity.RouteForm;
import com.eairlv.route.client.entity.RouteHandlerForm;
import com.eairlv.route.client.interceptor.RouteInterceptor;
import com.eairlv.route.demo.utils.BeanUtil;
import feign.Target;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author eairlv
 * @description
 * @date 14:18 2019/12/13
 */
@Configuration
@EnableConfigurationProperties(CustomRouteProperties.class)
public class CustomRouteConfig {

    @Autowired
    RouteProperties routeProperties;

    @Autowired
    CustomRouteProperties customRouteProperties;

    @Bean
    RouteInterceptor routeInterceptor(){
        return new CustomRouteInterceptor();
    }

    /**
     * List分组
     * @param key
     * @return
     */
    public String group(String key){
        for(Map.Entry<String, String> entry : customRouteProperties.getSession().entrySet()){
            // do something to choose session
            if (true){
                return entry.getValue();
            }
        }
        return routeProperties.getDefaultSession();
    }

    class CustomRouteInterceptor implements RouteInterceptor{

        @Override
        public String applyKey(Object o, Integer integer, Method method, Object[] objects, Target target) {
            return createKey(BeanUtil.copyProperties(o, CustomRoute.class));
        }

        @Override
        public Integer applyType(Object o, Integer integer, Method method, Object[] objects, Target target) {
            return routeProperties.getDefaultType();
        }

        @Override
        public RouteForm applyRoute(RouteHandlerForm routeHandlerForm, Method method, Object[] objects, Target target) {
            CustomRoute route = BeanUtil.copyProperties(routeHandlerForm.getKey(), CustomRoute.class);
            RouteForm routeForm = new RouteForm();
            routeForm.setKey(createKey(route));
            routeForm.setType(routeHandlerForm.getType());
            routeForm.setSession(routeProperties.getDefaultSession());
            for(Map.Entry<String, String> entry : customRouteProperties.getSession().entrySet()){
                // do something to choose session
                if (true){
                    routeForm.setSession(entry.getValue());
                }
            }
            return routeForm;
        }

        private String createKey(CustomRoute route){
            return route.getKey1() + "-" + route.getKey2();
        }
    }

}
